package com.lonefennec.chameleon.characters;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.lonefennec.chameleon.ChameleonGame;
import com.lonefennec.chameleon.Physics;

public class Guard extends WalkingActor
{	
	private Rectangle patrol;
	
	private boolean alarmed = false;
	
	public boolean isAlarmed()
	{
		return alarmed;
	}
	
	public float getVisionRange()
	{
		return 5.0f;
	}
	
	@Override
	public void act(float delta)
	{
		super.act(delta);
		
		if (patrol != null)
		{
			//can we see the player? if so, stop walking and raise the alarm level!
			float visionRange = getVisionRange();
			
			Rectangle vision = new Rectangle(x-width/2, y-height/2, visionRange, height);
			
			//if we're looking to the left, vision goes in the other direction
			if (isSpriteFlipped())
				vision.x -= (visionRange - width);
			
			Player player = ChameleonGame.player;
			
			Rectangle playerRect = new Rectangle();
			playerRect.x = player.x - player.width/2;
			playerRect.y = player.y - player.height/2;
			playerRect.width = player.width;
			playerRect.height = player.height;
			
			if (vision.overlaps(playerRect))
			{
				alarmed = true;
				isWalking = false;
			}
			else
			{
				alarmed = false;
				isWalking = true;
				
				if ((walkSpeed > 0 && x > patrol.x + (patrol.width - width / 2))
						|| (walkSpeed < 0 && x < (patrol.x + width / 2)))
				{
					walkSpeed = -walkSpeed;
				}
				
				if (walkSpeed > 0)
					setSpriteFlipped(false);
				else
					setSpriteFlipped(true);
			}
		}
		
		doWalk();
	}
	
	private Texture alarmIconTexture;
	
	@Override 
	public void draw(SpriteBatch batch, float parentAlpha)
	{
		super.draw(batch, parentAlpha);
		
		if (isAlarmed())
		{
			//the ! icon is scaled to the size of the sprite 
			float alarmIconScale = width / (Physics.SCREEN_TO_WORLD * alarmIconTexture.getWidth());
			float alarmIconHeight = Physics.SCREEN_TO_WORLD * alarmIconTexture.getHeight() * alarmIconScale;
			
			batch.draw(alarmIconTexture, x-width/2, y + alarmIconHeight, width, alarmIconHeight);
		}
	}
	
	@Override
	public Actor hit(float x, float y)
	{
		return null;
	}
	
	public Guard(Rectangle patrol)
	{
		super("sprites/guard.png", 1.15f, 1.10f, 80.0f);
		
		String alarmIconPath = "ui/alert.png";
		
		ChameleonGame.assets.load(alarmIconPath, Texture.class);
		ChameleonGame.assets.finishLoading();
		
		alarmIconTexture = ChameleonGame.assets.get(alarmIconPath, Texture.class);
		
		this.patrol = patrol;
		
		walkSpeed = 2;
		
		drawOffsetY = -0.05f;
	}
}
